package amdocs.jet.pm.currency;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;


import com.amdocs.jet.pm.R;
import org.xmlpull.v1.XmlSerializer;
import java.util.Calendar;

import amdocs.jet.pm.Constants;
import amdocs.jet.pm.CurrencyOptionType;
import amdocs.jet.pm.net.GetURLConnectionData;
import amdocs.jet.pm.xml.AllCurrencies;
import amdocs.jet.pm.xml.AndroidSaxCurrencyParser;
import amdocs.jet.pm.xml.Currency;
import amdocs.jet.pm.xml.CurrencyParser;
import android.app.ActivityManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CurrencyListActivity extends ListActivity 
{
	private TextView currencyHeaderTextView;
	private TextView currencyErrorTextView;
	private ArrayList<Currency> currencies = new ArrayList<Currency>();
	private AllCurrencies allCurrencies;
	private CurrencyArrayAdapter currencyListadapter;
	private ProgressDialog m_ProgressDialog = null;
	private Runnable viewRunnable;
	public static String URL_SITE;
    private int mYear;
    private int mMonth;
    private int mDay;
    private StringBuffer selectedDate;
    private boolean isParsePassSuccessfully;
    private String currencyDate;
    private String listHeaderTitle;
    private String errorText;

    private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() 
    {
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
            {
            	updateDate(year, monthOfYear, dayOfMonth);
    			URL_SITE = Constants.CURRENCY_BY_DATE_URL_CN + selectedDate.toString();
    			getAndParseCurrencies();
            }
    };
    
	
    @Override
    public void onCreate(Bundle icicle) 
    {
        super.onCreate(icicle);
        initDate();
        setContentView(R.layout.currency_screen);
        currencyHeaderTextView = (TextView) findViewById(R.id.currencyHeader);
        currencyErrorTextView = (TextView) findViewById(R.id.currencyError);
        this.currencyListadapter = new CurrencyArrayAdapter(this, R.layout.currency_item_list_row, currencies);
        setListAdapter(this.currencyListadapter);
        URL_SITE = Constants.TODAY_CURRENCY_URL_CN;
        getAndParseCurrencies();
    }
    
    private void postScreenRefresh() 
    {
        currencyHeaderTextView.setText(listHeaderTitle);
        if (isParsePassSuccessfully)
        {
            currencyErrorTextView.setHeight(0);
        }
        else
        {
            currencyErrorTextView.setHeight(30);
            currencyErrorTextView.setText(errorText);
        }
	}

	private Runnable returnRes = new Runnable() 
    {
        public void run() 
        {
        	currencyListadapter.clear();
        	currencyListadapter.notifyDataSetChanged();
            if(currencies != null && currencies.size() > 0)
            {
                for(int i=0;i<currencies.size();i++)
                {
                	currencyListadapter.add(currencies.get(i));
                }
            }
            m_ProgressDialog.dismiss();
            currencyListadapter.notifyDataSetChanged();
            postScreenRefresh();
        }
      };
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.currency_menu, menu);
		return true;
	}

	public boolean onMenuItemSelected(int featureId, MenuItem item) 
	{
		switch (item.getItemId()) 
		{
			case R.id.lastUpdateMenuItem:
		        URL_SITE = Constants.TODAY_CURRENCY_URL_CN;
		        getAndParseCurrencies();
				break;
			case R.id.previousUpdateMenuItem:
		        URL_SITE = Constants.PREVIOUS_CURRENCY_URL_CN;
		        getAndParseCurrencies();
				break;
			case R.id.byDateMenuItem:
				showDialog(Constants.DATE_DIALOG_ID);
				break;
			case R.id.currencySettingsMenuItem:
				Toast.makeText(this, "This option is not available", 7000).show();
				break;		
			case R.id.exitMenuItem:
				finish();
				break;			
			default:
				super.onMenuItemSelected(featureId, item);
				break;
		}
		return true;
	}
	

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
//		super.onListItemClick(l, v, position, id);
//		Intent viewMessage = new Intent(Intent.ACTION_VIEW, 
//				Uri.parse(currencies.get(position).getLink().toExternalForm()));
//		this.startActivity(viewMessage);
	}

	private void getAndParseCurrencies(){
    	try{
    		long start = System.currentTimeMillis();
    		
    	       viewRunnable = new Runnable() 
    	       {
    				public void run() 
    				{
    					CurrencyParser parser = new AndroidSaxCurrencyParser();
    			    	InputStream is = GetURLConnectionData.getAllInputStreamCurrencyData(URL_SITE);
    			    	allCurrencies = parser.parse(is);
    			    	postParser(allCurrencies);
    			    	currencies = allCurrencies.getCurrencies();
    					runOnUiThread(returnRes);
    				}
    			};
    			Thread thread = new Thread(null, viewRunnable, "Fetching Data");
    			thread.start();
    			m_ProgressDialog = ProgressDialog.show(CurrencyListActivity.this, "", "Please wait while retrieving...", true);
	    	long duration = System.currentTimeMillis() - start;
	    	Log.i("PersonalManager", "Parser duration=" + duration);
    	} catch (Throwable t){
    		Log.e("PersonalManager",t.getMessage(),t);
    	}
    }

	@Override
	protected Dialog onCreateDialog(int id) 
	{
	    switch (id) 
	    {
		    case Constants.DATE_DIALOG_ID:
		        return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
	    }
	    return null;
	}
	
	private static String pad(int c) 
	{
	    if (c >= 10)
	    {
	    	return String.valueOf(c);
	    }
	    else
	    {
	        return "0" + String.valueOf(c);
	    }
	}
	
	private void updateDate(int year, int monthOfYear, int dayOfMonth)
	{
        mYear = year;
        mMonth = monthOfYear;
        mDay = dayOfMonth;
        selectedDate = new StringBuffer();
        selectedDate.append(pad(mYear));
        selectedDate.append(pad(++mMonth));
        Log.i("PersonalManager", monthOfYear + "updateDate:mMonth=" + mMonth);
        selectedDate.append(pad(mDay));
        Log.i("PersonalManager", "updateDate:selectedDate=" + selectedDate);
	}
	
	private void initDate()
	{
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
	}
	
	private void postParser(AllCurrencies allCurrencies) 
	{
		if (allCurrencies.getRequestedDate() != null)
		{
			isParsePassSuccessfully = false;
			errorText = allCurrencies.getError2();
		}
		else
		{
			isParsePassSuccessfully = true;
		}
		currencyDate = allCurrencies.getCurrencyDate();
		System.err.println("Current Date: " + currencyDate);
		listHeaderTitle = getString(R.string.string_exchange_rate_date_title) + Constants.SPACE_STRING + currencyDate;
	}
	
	
    private class CurrencyArrayAdapter extends ArrayAdapter<Currency> {

        private ArrayList<Currency> items;
        private Bitmap iconFlag;

        public CurrencyArrayAdapter(Context context, int textViewResourceId, ArrayList<Currency> items) {
                super(context, textViewResourceId, items);
                this.items = items;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) 
        {
        	boolean isSALcurrency = false;
                View view = convertView;
                if (view == null) {
                    LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    view = vi.inflate(R.layout.currency_item_list_row, null);
                }
                Currency currency = items.get(position);
                if (currency != null) 
                {
	                ImageView imageView = (ImageView) view.findViewById(R.id.currencyIcon);
	                try 
	                {
						iconFlag = BitmapFactory.decodeStream(this.getContext().getAssets().open("currency/" + currency.getCurrencyCode().toLowerCase() + ".png"));
					} catch (IOException e) {
						e.printStackTrace();
					}
	
			        imageView.setImageBitmap(iconFlag);
	                		
	                TextView currencyCode = (TextView) view.findViewById(R.id.currency_code);
	                
	                if (currencyCode != null) 
	                {
	                	String unit = "";
	                	if (!currency.getUnit().equals("1"))
	                	{
	                		unit = currency.getUnit() + " ";
	                	}
	                	isSALcurrency = Constants.CURRENCY_BASKET_CODE.equals(currency.getCurrencyCode())?true:false;
	                	currencyCode.setText(unit + currency.getCurrencyCode());                            
	                }
	                TextView currencyRate = (TextView) view.findViewById(R.id.currency_rate);
	                if(currencyRate != null)
	                {
	                	currencyRate.setText(currency.getRate());
	                }
	                
	                TextView currencyNameAndCountry = (TextView) view.findViewById(R.id.currency_name_and_country);
	                if(currencyNameAndCountry != null)
	                {
	                	if (isSALcurrency)
	                	{
	                		currencyNameAndCountry.setText(currency.getName());
	                	}
	                	else
	                	{
	                		currencyNameAndCountry.setText(currency.getCountry() + " " + currency.getName());
	                	}
	                }
	                TextView currencyChange = (TextView) view.findViewById(R.id.currency_change);
	                if(currencyChange != null)
	                {
	                	
	                	currencyChange.setText(currency.getChange());                        	
	                	float change = Float.parseFloat(currency.getChange());
	                	int result = Float.compare(change, 0.0f);
	
	                	if (result > 0)
	                	{
	                		currencyChange.setTextColor(getResources().getColor(R.color.currency_evolution_up));
	                	}
	                	else if (change < 0)
	                	{
	                		currencyChange.setTextColor(getResources().getColor(R.color.currency_evolution_down));
	                	}
	                	else
	                	{
	                		currencyChange.setTextColor(getResources().getColor(R.color.currency_evolution_no_change));
	                	}
	                }
                }
                return view;
        }
    }
}